import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import './EchartsPie.scss'
import pieOption from './constant';
import { useIsMobile } from '@/hooks/useIsMobile'

export interface EchartsPieProps {
  height?: string,
  id: string,
  title: string,
  popoverPlacement?: string
  seriesData: any[],
}

const dynamicSetEchartsOptions = (isMobile: boolean, defOptions: any) => {
  const deepOptions = JSON.parse(JSON.stringify(defOptions))

  if (!isMobile) { //非移动端echarts  options设置
    deepOptions.title.textStyle.fontSize = "14px"
    deepOptions.series[0].label.fontSize = 12
  }

  return deepOptions
}

const EchartsPie: React.FC<EchartsPieProps> = (props) => {
  const isMobile = useIsMobile()
  const echartsPieOption = dynamicSetEchartsOptions(isMobile, pieOption)

  const h = !isMobile ? '300px' : props.height || '160px'
  const idName = props.id

  echartsPieOption.title.text = props.title
  echartsPieOption.series[0].data = props.seriesData

  const mycanvas = useRef<any>(null)
  // 获取dom 设置图像
  useEffect(() => {
    const myChart = echarts.init(document.getElementById(idName))
    mycanvas.current = myChart

    echartsPieOption && myChart.setOption(echartsPieOption)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  useEffect(() => { echartsPieOption && mycanvas.current.setOption(echartsPieOption) },)

  return (
    <div ref={mycanvas} style={{ height: h, width: "100%" }} id={idName}></div>
  )
}

export default EchartsPie